import { FC, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { Typography, Space, Form, Input, Button, Checkbox, message } from "antd";
import { useRequest } from "ahooks";
import { UserAddOutlined } from "@ant-design/icons";
import { MANAGE_INDEX_PATHNAME, REGISTER_PATHNAME } from "../router";
import { loginService } from "../services/user";
import { setToken } from "../utils/user-token";
import styles from "./Register.module.scss";
const { Title } = Typography;
const USERNAME_KEY = "USERNAME";
const PASSWORD_KEY = "PASSWORD";

function rememberUser(username: string, password: string) {
  localStorage.setItem(USERNAME_KEY, username);
  localStorage.setItem(PASSWORD_KEY, password);
}

function deleteUser() {
  localStorage.removeItem(USERNAME_KEY);
  localStorage.removeItem(PASSWORD_KEY);
}
function getUserInfo() {
  return {
    username: localStorage.getItem(USERNAME_KEY),
    password: localStorage.getItem(PASSWORD_KEY),
  };
}
const Login: FC = () => {
  const nav=useNavigate()
  const [form] = Form.useForm(); //Form 第三方hook
  useEffect(() => {
    const { username, password } = getUserInfo();
    form.setFieldsValue({ username, password });
  }, [form]);
  //登录
  const {run:login}=useRequest(async(username, password)=>{
    const data=await loginService(username, password)
    return data 

  },{manual:true,onSuccess(result){
      message.success('登录成功')
      setToken(result.token)//存储token
      nav(MANAGE_INDEX_PATHNAME) //跳转到我的问卷页面
  }})
  const onFinish = (values: any) => {
    const { username, password, remember } = values || {};
    login(username, password)
    if (remember) {
      rememberUser(username, password);
    } else {
      deleteUser();
    }
  };
  return (
    <div className={styles.container}>
      <div>
        <Space>
          <Title level={2}>
            <UserAddOutlined />
          </Title>
          <Title level={2}> 登录</Title>
        </Space>
      </div>

      <div>
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          initialValues={{ remember: true }}
          form={form}
        >
          <Form.Item label="用户名" name="username">
            <Input />
          </Form.Item>
          <Form.Item label="密码" name="password">
            <Input.Password />
          </Form.Item>
          <Form.Item name="remember" valuePropName="checked">
            <Checkbox>记住我</Checkbox>
          </Form.Item>
          <Form.Item wrapperCol={{ span: 16, offset: 6 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
              <Link to={REGISTER_PATHNAME}>注册新用户</Link>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
export default Login;
